﻿using System.Text.Json;
using IMServer.Models.Message;
using IMServer.Services;

namespace IMServer.WebSocketServices
{
    public static class WebSocketMessageHandle
    {
        public static async Task HandleMessage(string message)
        {
            try
            {
                // 解析为 JSON 对象获取消息类型
                var baseMessageJson = JsonDocument.Parse(message).RootElement;
                if (!baseMessageJson.TryGetProperty("MessageType", out var messageTypeElement))
                {
                    Console.WriteLine("Invalid message format: missing messageType");
                    return;
                }

                var messageType = messageTypeElement.GetString();
                if (messageType == null)
                {
                    Console.WriteLine("Invalid message format: messageType is null");
                    return;
                }

                BaseMessage? chatMessage;

                // 根据类型动态解析为具体子类
                if (messageType == "CHAT")
                {
                    var chatType = baseMessageJson.TryGetProperty("ChatType", out var chatTypeElement)
                        ? chatTypeElement.GetString()
                        : "private";

                    if (chatType == "group")
                    {
                        chatMessage = JsonSerializer.Deserialize<GroupChatMessage>(message);
                    }
                    else
                    {
                        chatMessage = JsonSerializer.Deserialize<ChatMessage>(message);
                    }
                }
                else
                {
                    Console.WriteLine($"Unsupported messageType: {messageType}");
                    return;
                }

                if (chatMessage == null)
                {
                    Console.WriteLine("Invalid message: deserialization failed");
                    return;
                }

                chatMessage.GenerateMessageId();

                // 私聊或群聊消息转发
                if (chatMessage is GroupChatMessage groupMessage)
                {
                    var group = await GroupDbService.Instance.GetGroupByIdAsync(groupMessage.GroupId);
                    var groupMembers = group.Members.ToList();
                    foreach (var memberId in groupMembers.Where(memberId => memberId != groupMessage.SenderId))
                    {
                        var isSuccess = await WebSocketManager.Instance.SendMessageToUserAsync(
                            memberId,
                            groupMessage.ToJson()
                        );

                        if (isSuccess)
                        {
                            Console.WriteLine($"Message sent to group member {memberId}");
                        }

                        // 存储消息到数据库
                        await MessageBoxDbService.Instance.InsertMessageAsync(
                            memberId,
                            chatMessage
                        );
                    }
                }
                else if (chatMessage is ChatMessage privateMessage)
                {
                    //不知道为什么这样就能正常跑
                    chatMessage = JsonSerializer.Deserialize<GroupChatMessage>(message) ??
                                  throw new InvalidOperationException();

                    var isSuccess = await WebSocketManager.Instance.SendMessageToUserAsync(
                        privateMessage.ReceiverId,
                        chatMessage.ToJson()
                    );

                    if (isSuccess)
                    {
                        Console.WriteLine($"Message sent to user {privateMessage.ReceiverId}");
                    }

                    // 存储消息到数据库
                    await MessageBoxDbService.Instance.InsertMessageAsync(
                        privateMessage.ReceiverId,
                        privateMessage
                    );
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error handling message: {ex.Message}");
            }
        }
    }
}